from .conn_mysql import Connect_Mysql

from .phone_test import is_phone,register_name
from .name_test import is_name

import pymysql

from flask import request

from . import app_register

@app_register.route('/register',methods = ['POST'])

def register():

    info = request.form
    company_name = info.get('company_name')
    linkman = info.get('linkman')
    phone = info.get('phone')
    need = info.get('need')
    party = info.get('party')
    openid = info.get('openid')

    sql = 'insert into company(company_name,linkman,phone,need,party)values(%s,%s,%s,%s,%s)'

    if not all((company_name,linkman,phone,need,party)):#and not is_phone(phone):

        return {
                    'status': -1,
                    'errorCode': '1',
                    'errorMsg': '参数错误',
                    'resultBody': None
                }
    
    if not register_name(company_name):

        return {
                    'status': -1,
                    'errorCode': 5,
                    'errorMsg': f'请检查你company_name：{company_name}，格式错误',
                    'resultBody': None
                }

    if not is_name(linkman):

        return {
            'status': -1,
            'errorCode': 4,
            'errorMsg': f'请检查你linkman：{linkman}必须是中文',
            'resultBody': None
        }



    # if not register_name(linkman):

    #     return {
    #                 'status': -1,
    #                 'errorCode': 4,
    #                 'errorMsg': f'请检查你linkman：{linkman}，格式错误',
    #                 'resultBody': None
    #             }


    if not is_phone(phone):

        return {
                    'status': -1,
                    'errorCode': 2,
                    'errorMsg': f'请检查你的phone：{phone}',
                    'resultBody': None
                }

    if len(need)>= 10 and type(len)!= int:

        with Connect_Mysql() as conn_:

            try:

                info = conn_.insert_company(sql,(company_name,linkman,phone,need,party))
            
            except pymysql.err.IntegrityError as e: #: (1062, "Duplicate entry '77771231231' for key 'phone'")

                if e.args[0] == 1062:
                    return {
                        'status': -1,
                        'errorCode': 1062,
                        'errorMsg': e.args[1],
                        'resultBody': None
                    }

                else:
                    raise

            conn_.update_openid(openid,info['LAST_INSERT_ID()'])
            
        return {
                    'status': 1,
                    'errorCode':  None,
                    'errorMsg': None,
                    'resultBody':   info['LAST_INSERT_ID()']
                }

    else:

        return {
                    'status': -1,
                    'errorCode':  '3',
                    'errorMsg': f'{need}不够完善，请重新提交,并且完善',
                    'resultBody': None
                }